/*******************************************************************************
*  Project      : Minigate Golfin                                 
*  Program ID   : home.js                                 
*  Description  : 클럽개별메인 
*
********************************************************************************
*  Program History                                                            
*  Date        Author    Description                                          
*  ----------  --------  -------------------------------------------------------- 
*  2012-06-14  이윤노    Created.  
*  2012-06-14  이윤노    Complete.    
*******************************************************************************/

jQuery(function($){
	
	// 내용
	function clsNote()
	{
		this._HTMLDom = null;
		this.wirteData = null;
		
		this.errMsg = null;
		this._ERRMSG = {
			"_TITLE": "제목을 입력해 주십시요."
			, "_CONTENT": "내용을 입력해 주십시요."
			, "_OPEN": "공개설정을 선택하여 주십시요."
		}
		
		this._init();
	}
	
	clsNote.prototype = {
		_init: function(){
			var $layer = $("div#container section#main_content table");
			var thisClass = this;
			
			this._HTMLDom = {
				"$layer": $layer
			}
			
			$layer.find("tr:eq(1) td").prepend("<textarea />");
			
			fnLoadingJS("../inc/ckeditor_3.6.3/ckeditor.js", function(){
				fnLoadingJS("../inc/ckeditor_3.6.3/adapters/jquery.js", function(){
					thisClass._CKEditor();
				});
			});
			
			$layer.find("input:radio:first").prop("checked",true);
		}
		, _CKEditor: function(){
			var thisClass = this;
			var ckOption = _gf.getCKClubOption();
			
			this._HTMLDom["$layer"].find("textarea").ckeditor(ckOption);
			
			// 에디터 준비완료
			this.$getEditor().ckeditorGet().on("instanceReady", function(){				
				_gf.setCKEditorUploadFileButton(this, function(ret){
					document.objControl.finishUploadFile(ret);
				});
			});
		}
		, focus: function(){
			this.$getEditor().ckeditorGet().focus();
		}
		, $getEditor: function(){
			return this._HTMLDom["$layer"].find("textarea");
		}
		, getValue: function(){
			var $layer = this._HTMLDom["$layer"];
			
			var aRet = {
				"제목": $layer.find("tr:eq(0) td input:text").val()
				, "내용": this.$getEditor().val()
				, "공지유무": ($layer.find("tr:eq(0) td input:checkbox").prop("checked")?"Y":"N")
				, "공개유무": 	($layer.find("input:radio").index($("input:radio:checked"))?"C":"A")
			}
			
			return aRet;
		}
		, setValue: function(thisData){
			var $layer = this._HTMLDom["$layer"];
			
			var szTitle = $layer.find("tr:eq(0) td input:text");
			var szContent = this.$getEditor();
			var szNotice = $layer.find("tr:eq(0) td input:checkbox");
			var szViewType = $layer.find("input:radio");
			
			szTitle.val(thisData["제목"]);
			szContent.val(thisData["내용"]);
			szNotice.prop("checked",(thisData["공지유무"]=="Y"?true:false));
			szViewType.eq((thisData["공개유무"]=="A"?0:1)).prop("checked",true);			
		}
		, isVaild: function(){
			var $layer = this._HTMLDom["$layer"];
			
			if($layer.find("tr:eq(0) td input:text").val() ==""){
				this.errMsg = this._ERRMSG["_TITLE"];
				return false;
			}else if(this.$getEditor().val() == ""){
				this.errMsg = this._ERRMSG["_CONTENT"];
				return false;
			}else if($layer.find("input:radio").index($("input:radio:checked")) < 0){
				this.errMsg = this._ERRMSG["_OPEN"];
				return false;	
			}
			return true;
		}
		, getError: function(){
			return this.errMsg;
		}
		, insertImage: function(szImage){
			this.$getEditor().ckeditorGet().insertHtml("<img src='" + szImage + "' />");
		}
			
	}
	
	// 업로드파일
	function clsUploadFile()
	{
		this.listData = null;
		
		this._init();
	}
	
	clsUploadFile.prototype = {
		_init: function(){
			this.setList([]);
		}
		, setList: function(thisData){
			this.listData = thisData;
		}
		, push: function(oneData){
			if(!oneData["키"]) oneData["키"] = "NOT";
			if(!oneData["섬네일"]) oneData["섬네일"] = "NOT";
			
			this.listData.push(oneData);
		}
		, getList: function(){
			return this.listData;
		}
		, sync: function(note){
			for(var i=0;i<this.listData.length;i++){
				var targetURL = "";
				
				if(this.listData[i]["키"] == "NOT"){
					targetURL = this.listData[i]["파일명"].replace(_UPLOADPATH_TMP, _UPLOADURL_TMP);
				}else{
					targetURL = this.listData[i]["파일명"].replace(_UPLOADPATH, _UPLOADURL);
				}
				
				var reg = new RegExp(targetURL, "gi");
				
				if(!reg.test(note)){
					this.listData.splice(i, 1);
					i--;
				}
			}
		}
		, getValue: function(){
			var szRet = "";
			
			for(var i=0;i<this.listData.length;i++){
				if(szRet) szRet += ",";
				
				szRet += this.listData[i]["키"] + "," + this.listData[i]["섬네일"] + "," + this.listData[i]["파일명"] + "," + this.listData[i]["원본파일명"];
			}
			
			return szRet;
		}
	}
	
	function clsComm()
	{
		this.clubBoardView=null;
		this.clubBoardViewRequest=null;
		
		this._init();
	}
	
	clsComm.prototype = {
		_init: function(){
			
			this.clubBoardViewRequest = {
				"동호회키": null
				, "게시판키": null
			}
		}
//------------------------수정글정보조회------------------------//		
		, getClubBoardView: function(){			
			var thisClass = this;
			
			var szBoardSeq = this.clubBoardViewRequest["게시판키"];
				
			// ajax 시작			
			//parameter setting and run
			_gf.ajax({
				"sid":"CB001",
				"servicename":"getDetailClubBoard"
			}, {
				  "board_seq": szBoardSeq
				  , "modpage_yn": "N"
			}, function(ret){
				
				// callback and mapping
				if(ret["msp"]["contents"]["items"]){
					var arr = [];
					var obj = ret["msp"]["contents"]["items"];
					
					var reg_date = obj["reg__date"]+"";
					var reg_time = obj["reg__time"]+"";
					var fileBean = obj["FileBean"];
					
					var aFileList = [];
					
					if(fileBean){
						for(var i=-0;i<fileBean.length;i++){
							var objFile = fileBean[i]["items"];
							aFileList.push({
								"파일키": objFile["file__seq"]
								, "섬네일": objFile["thumb"]
								, "파일명": objFile["path"] + objFile["save__file__name"]
								, "원본파일명": objFile["orgn__file__name"]
							});
						}
					}
					
		
					//게시글상세정보
					thisClass.clubBoardView = {
						"동호회키": obj["board__seq"]
						, "제목": obj["title"]
						, "내용": obj["content"]
						, "공개유무": obj["view__type"]
						, "공지유무": obj["notice__yn"]
						, "파일리스트": aFileList							
					};
				}         

				$(thisClass).trigger("evtFinishClubBoardView");
			});
		}
		, getClubBoardViewData: function(){
			return this.clubBoardView;
		}
		, setClubBoardViewRequest: function(key,val){
			this.clubBoardViewRequest[key]=val;	
		}
//------------------------수정글정보조회------------------------//		
//------------------------ 글등록/수정------------------------//		

		, InsertBoardData: function(arg){			
			var thisClass = this;
			
			var szClubSeq = arg["동호회키"];
			var szBoardSeq = arg["게시판키"];
			var szTitle = arg["제목"].replace(/"/g, "\\\"");
			var szContent = arg["내용"].replace(/\n/g,"").replace(/"/g, "\\\"");
			var szViewType = arg["공개유무"];
			var szNotice = arg["공지유무"];
			var szFile = arg["파일리스트"]
			var szModule = !arg["게시판키"]?"regClubBoard":"updateClubBoard";
			// ajax 시작			
			//parameter setting and run
			_gf.ajax({
				"sid":"CB001",
				"servicename": szModule
			}, {
				"board_type": "D"
				, "club_seq": szClubSeq
				, "board_seq": szBoardSeq
				, "title": szTitle
				, "content": szContent
				, "view_type": szViewType //A : 전체 / C: 동호회
				, "notice_yn": szNotice				
				, "file_list": szFile
				, "file_list_attach": ""
				
			}, function(ret){				
				
				// callback and mapping
				var resData = {
					"응답코드": (ret["msp"]["contents"]["serviceResult"] == "00000"?true:false)
					, "메세지": _gf.getResultMsg(ret)
				}
				
				$(thisClass).trigger("evtFinishClubSubmit", [resData]);
				
			});
			// ajax 끝
		}
//------------------------ 글등록------------------------//	
	}
	
	function clsControl()
	{
		this.club_seq = null;
		this.club_my = null;
		
		this.objComm = null;
		this.objClubInfo = null;
		this.objRole = null;
		this.objNote = null;
		this.objUploadFile = null;
		
		this._init();		
	}
	
	clsControl.prototype = {
		_init: function(){
			var member_id = _util.getCookie("member_id");
			this.club_seq = _util.getParam("club_seq");
			this.club_my = _util.getParam("club_my");
			this.board_seq = _util.getParam("board_seq");
			
			if(!member_id) {
				if(confirm("로그인 후 이용하여 주세요.")){
					_gf.goLogin();						
				}else{
					document.location.href = "../club/club.html";
				}
			}else if(!this.club_seq) {
				document.location.href = "../club/club.html";
			}
			
			this._preload();
			
			this.objComm = new clsComm();
			this.objNote = new clsNote();
			this.objUploadFile = new clsUploadFile();
			
			this._beforeStart();
			this._bind();
		}
		, _preload: function(){
			_gf.spinStart();
		}
		, _beforeStart: function(){
			var thisClass = this;
			this._permitStart = {
				
			}
			
			$.ajax({
				url: "js/self_club_top.js"
				, dataType: "script"
				, async: false
				, success: function(){
					
				}
				, error: function(){
					alert("error");
				}
			});
			
			_util.executeThread(function(){
				for(var k in thisClass._permitStart){
					if(!thisClass._permitStart[k]) return false;
				}
				
				return (_clubControl.getClubInfo().infoData);
			}, function(){				
				_gf.spinEnd();;
				thisClass._start();
			});	
		}
		, _role: function(){			
			//기능제어			
			if(!this.objRole.isAdmin()){
				//글삭제
				$("div.golf_board  article.btn_area a").hide();
				$("input:checkbox").hide();
				$(".ma_left5").hide();
			}			
		}		
		, _start: function(){		
			this.objClubInfo = _clubControl.getClubInfo();
			this.objRole = new clsRole(this.objClubInfo.infoData);
			this._role();
			
			//글정보 받아오기
			if(this.board_seq){
				_gf.spinStart("receiving...");					
				
				//수정글정보 조회
				this.objComm.setClubBoardViewRequest("동호회키", this.club_seq);
				this.objComm.setClubBoardViewRequest("게시판키", this.board_seq);
				this.objComm.getClubBoardView();			
			}
		}
		, _bind: function(){
			var thisClass = this;
			
			//게시글 등록 완료이벤트
			$(this.objComm).bind("evtFinishClubSubmit", function(event, resData){				
				alert(resData["메세지"]);				
				if(resData["응답코드"]){				
					_gf.spinEnd();					
					document.location.href = "club_list.html" + thisClass.returnParam();
				}			
			});
			
			// 게시글상세정보 조회 완료이벤트
			$(this.objComm).bind("evtFinishClubBoardView", function(){
				var thisData = thisClass.objComm.getClubBoardViewData();
				thisClass.objNote.setValue(thisData);				
				thisClass.objUploadFile.setList(thisData["파일리스트"]);
				_gf.spinEnd();
			});
			
			//확인
			$("div#container p.btn_center img[alt=확인]").click(function(event){
				
				var submitData = thisClass.objNote.getValue();
				var szUploadFile = thisClass.objUploadFile.getValue();
				
				submitData["동호회키"] = thisClass.club_seq;
				submitData["게시판키"] = thisClass.board_seq;
				submitData["파일리스트"] = szUploadFile;
				
				if(!thisClass.objNote.isVaild()){
					alert(thisClass.objNote.getError());
					return;
				}
				thisClass.objComm.InsertBoardData(submitData);								
			});
			
			//취소
			$("div#container p.btn_center img[alt=취소]").click(function(event){
				document.location.href = "club_list.html" + thisClass.returnParam();
			});
			
			//공지유무
			$("div#container section#main_content div table tbody tr td input:checkbox").click(function(event){
				var $checkbox = $("div#container section#main_content div table tbody tr td input:checkbox");
								
				if(!thisClass.objClubInfo.objRole.isAdmin()){
					alert(thisClass.objClubInfo.objRole.getError());
					$checkbox.prop("checked", false);
				}
			});
		}
		// 이미지 업로드
		, finishUploadFile: function(ret){
			this.objNote.insertImage(ret["파일리스트"][0]["파일명"].replace(_UPLOADPATH_TMP, _UPLOADURL_TMP));

			this.objUploadFile.push(ret["파일리스트"][0]);
		}
		, returnParam: function(){
			return "?club_seq="  + this.club_seq + "&club_my=" + this.club_my;
		}
	}
	
	document.objControl = new clsControl();
});